import fs from 'fs';
import path from 'path'
import pool from '../database/index.js'
import { SplicingImagePaths } from '../utils/tools.js'



/**获取用户资料 */
export const getUserProfile = async(req,res)=>{
    const { userId } = req
    const [results,fields] = await pool.execute(`SELECT * FROM user_info WHERE userId=${userId}`)
    if(!results.length) return res.status(400).send({ code:400,msg:'请求错误',data:{ message:'用户不存在' } })
    const info = results[0]
    const user = SplicingImagePaths(info)
    res.send({ msg:'请求成功',code:200,data:{ message:'用户资料获取成功',user  } })
}

/**获取用户路由权限 */
export const getUserPerm = async(req,res)=>{
    const { userId } = req
    try {
        const [results,fields] = await pool.execute(`SELECT field AS perm  from user_role 
            INNER JOIN role_perm ON user_role.roleId = role_perm.roleId 
            INNER JOIN permission ON role_perm.permId=permission.id WHERE user_role.userId=${userId}`)
            const list = results.map(val=>val.perm)
         res.send({ msg:'请求成功',code:200,data:{ message:'用户权限获取成功',list  } }) 
    } catch (error) {
        console.log(`接口${req.path}出现错误,错误为${error}`)
        res.status(400).send({ msg:'请求失败',code:400,data:{ message:'权限查询失败'  }  })
    }
}   


/**更改用户资料 */
export const updateUserProfile = async(req,res)=>{
    const { userId } = req
    const paramList = ['nickname','age','intro']
    //筛选出已传参数
    const keys = Object.keys(req.body).filter(val=>{
         if(req.body[val] && paramList.includes(val)) return val
    })
    if(!keys.length) return res.status(500).send({ msg:'请求失败',code:400,data:{ message:'参数错误'  }  })
    //将传入的参数拼接为字符串
    const str = keys.map(item=> {
        if(item == 'age') return `${item}=${req.body[`${item}`]}`
        return `${item}='${req.body[`${item}`]}'`    
    })
    try{
        await pool.execute(`UPDATE  user_info SET ${str.join(',')} WHERE userId=${userId} `)
        res.send({ msg:'修改成功',code:200,data:{ message:'修改成功'  } })
    }catch(error){
        console.log(`接口${req.path}出现错误,错误为${error}`)
        res.status(400).send({ msg:'修改失败',code:400,data:{ message:'修改成失败'  }  })
    }
}


/**修改头像 */
export const updateUserAvatar = async(req,res)=>{
    const { userId } = req
    const { file } = req.files
    const { name } = req.body
    //数据库存储地址
    const imgUrl = `/image/avatar/${encodeURIComponent(name)}`
    const dist = path.resolve(`./assets/avatar/${encodeURIComponent(name)}`)
    fs.rename(file.path,dist,async(err)=>{
         if(err) return res.status(400).send({ code:400,msg:'请求失败',data:{ message:'头像上传失败' + err } })
         try{
            await pool.execute(`UPDATE user_info SET avatar='${imgUrl}' WHERE userId=${userId} `)
            res.send({ code:200,msg:'请求成功',data:{ message:'头像上传成功' } })
        }catch(error){
            console.log(`接口${req.path}出现错误,错误为${error}`)
            res.status(400).send({ code:400,msg:'请求失败',data:{ message:'头像上传失败' } })
        }
    }) 
}